package com.jms.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * create by yongli on 2021-06-04 14:34
 * 两个时间库对象，要各自扫描各自的
 * <p>
 * file [/Users/yongli/project/services/midware/target/classes/com/jms/mapper/UserMapper.class] required a single bean,
 * but 2 were found:
 * - localSqlSessionFactory: defined by method 'getLocalSqlSessionFactory' in class path resource
 * [com/jms/config/LocalSqlSessionFactoryConfig.class]
 * - remoteSqlSessionFactory: defined by method 'getRemoteSqlSessionFactory' in class path resource
 * [com/jms/config/RemoteSqlSessionFactoryConfig.class]
 * <p>
 * 否则IUserService会加载两遍
 */
@Configuration
@MapperScan(basePackages = "com.jms.remote", sqlSessionFactoryRef = "remoteSqlSessionFactory")
public class RemoteSqlSessionFactoryConfig {


    @Autowired
    @Qualifier("remoteDataSource")
    DataSource remoteDatasource;


    // 对象交个spring托管
    // 但是其
    @Bean(name = "remoteSqlSessionFactory")
    public SqlSessionFactoryBean getRemoteSqlSessionFactory() {
        // SqlSessionFactory本身没有去读取数据库配置的代码，需要手动或者spring-boot的方式
        // 这是纯mybatis的用法
        // SqlSessionFactory factoryBean = new SqlSessionFactoryBuilder().build(configuration)
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(remoteDatasource);

        return factoryBean;
    }


//    @Bean
//    public SqlSessionFactory sqlSession() {
//        try {
//
//            return getSqlSessionFactory().getObject();
//        } catch (Exception e) {
//            return null;
//        }
//    }

}
